'''
程序入口
数据加载
算法执行流程控制
结果展示
'''
import sys
import Globals
import Utils
import MOSL
import os

distance_file = ''
time_file = ''
spec_file = ''
stop_time = 0
iter_time = 0


# 解析命令行参数
def parse_args():
    # 输出命令行参数
    # print("命令行参数:", sys.argv)

    # 第一个参数是脚本的名称
    # script_name = sys.argv[0]
    # print("脚本名称:", script_name)

    # arguments = sys.argv[1:]
    # print("用户传入的参数:", arguments)

    # 检查命令行参数数量是否小于6，如果是，则打印错误信息并退出程序
    if len(sys.argv) < 7:
        print("Specify data and output files")
        sys.exit(1)
    # 获取距离文件，时间文件，规格文件的名字
    global distance_file, time_file, spec_file, stop_time, customer_num, iter_time
    distance_file = sys.argv[1]
    time_file = sys.argv[2]
    spec_file = sys.argv[3]

    # 从命令行参数中获取停止时间和客户数量
    stop_time = int(sys.argv[5])
    Globals.customer_num = int(sys.argv[6])
    iter_time = int(sys.argv[7])


if __name__ == '__main__':
    parse_args()
    Utils.get_data(distance_file, time_file, spec_file)

    out_dir = sys.argv[4]
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    for i in range(iter_time):
        # 结果输出文件
        out_file = "result" + str(i + 1) + ".txt"
        full_out_path = os.path.join(out_dir, out_file)
        with open(full_out_path, "w") as file:
            # sys.stdout = file  # 重定向标准输出到文件
            MOSL.process(stop_time)
            Utils.output(file)
            for solution in Globals.EP:
                MOSL.update_best(solution)
            result = Utils.check_EP()
            # print(f"EP约束检查结果：{result}")
            # sys.stdout = sys.__stdout__  # 恢复标准输出到控制台

        subfolder = "result" + str(i + 1) + "_route"
        subfolder_path = os.path.join(out_dir, subfolder)
        os.makedirs(subfolder_path, exist_ok=True)
        for j, chromo in enumerate(Globals.EP):
            full_out_path = os.path.join(subfolder_path, f"route{j + 1}.txt")
            with open(full_out_path, 'w') as f:
                for route in chromo.routes:
                    route_row = " ".join(map(str, route.customers))
                    # 将每一行写入文件
                    f.write(route_row + "\n")

                    data = [len(route.customers) - 2, int(route.travel_dist), int(route.travel_time),
                            int(route.wait_time),
                            int(route.delay_time), int(route.delivery_capacity), int(route.pick_up_capacity)]
                    route_row = " ".join(map(str, data))
                    f.write(route_row + "\n")

        Globals.EP.clear()

    #  最佳结果输出文件
    final_file = "final.txt"
    full_out_path = os.path.join(out_dir, final_file)
    with open(full_out_path, "w") as file:
        Utils.output_best(file)

    final_folder = "final" + "_route"
    final_folder_path = os.path.join(out_dir, final_folder)
    os.makedirs(final_folder_path, exist_ok=True)
    for j, chromo in enumerate(Globals.total_best):
        full_out_path = os.path.join(final_folder_path, f"route{j + 1}.txt")
        with open(full_out_path, 'w') as f:
            for route in chromo.routes:
                route_row = " ".join(map(str, route.customers))
                # 将每一行写入文件
                f.write(route_row + "\n")

                data = [len(route.customers) - 2, int(route.travel_dist), int(route.travel_time),
                        int(route.wait_time),
                        int(route.delay_time), int(route.delivery_capacity), int(route.pick_up_capacity)]
                route_row = " ".join(map(str, data))
                f.write(route_row + "\n")

    # final_result = [0, 0, 0, 0, 0]
    # for i in range(Globals.FUNC_NUM):
    #     for chromo in Globals.total_best:
    #         final_result[i] += chromo.f[i]
    #     final_result[i] = final_result[i] / len(Globals.total_best)
    # final_file = "final_result.txt"
    # full_out_path = os.path.join(out_dir, final_file)
    # with open(full_out_path, "w") as file:
    #     print(final_result, file=file)

    # Utils.print_extreme_info()
